<template>
  <view class="basic tn-safe-area-inset-bottom">
    <view class="top-backgroup">
      <image
        src=""
        mode="widthFix"
        class="backgroud-image"
      >
      </image>
    </view>

    <!-- 页面内容 -->
    <view
      class="tn-margin-left tn-margin-right"
      :style="{ paddingTop: vuex_custom_bar_height + 'px' }"
    >
      <!-- 图标logo/头像 -->
      <view class="tn-margin-bottom" style="margin-top: -450rpx">
        <view class="justify-content-item">
          <view class="tn-flex tn-flex-row-left tn-margin-left item-container">
            <view class="logo-pic">
              <view class="logo-image">
                <view
                  class="tn-shadow-blur"
                  style="
                    background-image: url('/static/84a24bb8b4854c633e85ee15c18737b1.png');
                    width: 110rpx;
                    height: 110rpx;
                    background-size: contain;
                  "
                >
                  <!-- <tn-avatar  size="lg" src="/static/84a24bb8b4854c633e85ee15c18737b1.png" mode="aspectFit"></tn-avatar> -->
                </view>
              </view>
            </view>
            <view class="tn-padding-right">
              <view class="tn-padding-right tn-padding-left-sm">
                <text class="tn-color-wallpaper tn-text-xl tn-text-bold">{{
                  username
                }}</text>
              </view>
              <view
                class="tn-padding-right tn-padding-top-xs tn-padding-left-sm tn-text-ellipsis"
              >
                <text class="tn-color-gray--dark">努力吃奶</text>
                <i
                  style="
                    color: rgb(255, 255, 255);
                    opacity: 0.8;
                    font-size: 32rpx;
                    margin-left: 10rpx;
                  "
                  :class="`qi-${weatherIcon}`"
                ></i>
                <span
                  v-if="weatherTemp"
                  style="
                    color: rgb(255, 255, 255);
                    opacity: 0.8;
                    font-size: 11px;
                    margin-left: 5rpx;
                    vertical-align: top;
                  "
                  >{{ weatherTemp }}°</span
                >
              </view>
              <view
                class="tn-padding-right tn-padding-top-xs tn-padding-left-sm tn-text-ellipsis"
              >
                <text v-if="birthday">出生 {{ birthday }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="tn-flex tn-margin-sm">
          <view
            class="tn-flex-1 tn-padding-sm tn-margin-xs tn-radius"
            @tap="navigateTo('milk_record')"
          >
            <view
              class="tn-flex tn-flex-direction-column tn-flex-row-center tn-flex-col-center"
            >
              <view
                class="icon12__item--icon tn-flex tn-flex-row-center tn-flex-col-center tn-shadow-blur tn-main-gradient-purplered--light tn-color-purplered"
              >
                <view class="tn-icon-like-fill tn-three"></view>
              </view>
              <view class="tn-color-black tn-text-center">
                <text class="tn-text-ellipsis">喂奶记录</text>
              </view>
            </view>
          </view>
          <view
            class="tn-flex-1 tn-padding-sm tn-margin-xs tn-radius"
            @tap="navigateTo('vaccine')"
          >
            <view
              class="tn-flex tn-flex-direction-column tn-flex-row-center tn-flex-col-center"
            >
              <view
                class="icon12__item--icon tn-flex tn-flex-row-center tn-flex-col-center tn-shadow-blur tn-main-gradient-indigo--light tn-color-indigo"
              >
                <view
                  style="width: 55rpx; height: 55rpx"
                  class="tn-three t-icon t-icon-yimiao"
                ></view>
              </view>
              <view class="tn-color-black tn-text-center">
                <text class="tn-text-ellipsis">疫苗</text>
              </view>
            </view>
          </view>
          <view
            class="tn-flex-1 tn-padding-sm tn-margin-xs tn-radius"
            @tap="navigateTo('child_care')"
          >
            <view
              class="tn-flex tn-flex-direction-column tn-flex-row-center tn-flex-col-center"
            >
              <view
                class="icon12__item--icon tn-flex tn-flex-row-center tn-flex-col-center tn-shadow-blur tn-main-gradient-purple--light tn-color-purple"
              >
                <view
                  style="width: 73rpx; height: 73rpx"
                  class="t-icon t-icon-ertongbaojian1 tn-three"
                >
                </view>
              </view>
              <view class="tn-color-black tn-text-center">
                <text class="tn-text-ellipsis">儿保</text>
              </view>
            </view>
          </view>
          <view
            class="tn-flex-1 tn-padding-sm tn-margin-xs tn-radius"
            @tap="navigateTo('growth_record')"
          >
            <view
              class="tn-flex tn-flex-direction-column tn-flex-row-center tn-flex-col-center"
            >
              <view
                class="icon12__item--icon tn-flex tn-flex-row-center tn-flex-col-center tn-shadow-blur tn-main-gradient-orange--light tn-color-orange"
              >
                <view class="tn-icon-statistics-fill tn-three"></view>
              </view>
              <view class="tn-color-black tn-text-center">
                <text class="tn-text-ellipsis">成长记录</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <multiple-options-demo
        :list="groupList"
        @add="addPopup"
      ></multiple-options-demo>
    </view>
    <view :style="{ paddingTop: vuex_custom_bar_height + 'px' }">
      <tn-toast ref="toast"></tn-toast>
    </view>

    <!-- popup -->
    <record-popup
      :show="show"
      :type="index"
      :mode="mode"
      :backgroundColor="backgroundColor"
      :width="width"
      :height="height"
      :borderRadius="23"
      :closeBtn="closeBtn"
      :closeBtnIcon="closeBtnIcon"
      :closeBtnPosition="closeBtnPosition"
      :maskCloseable="maskCloseable"
      :db="Db"
      @close="closedPopup"
      @save="save"
    />
  </view>
</template>

<script>
import dynamicDemoTemplate from "@/libs/components/dynamic-demo-template.vue";
import multipleOptionsDemo from "@/libs/components/multiple-options-demo";
import timePicker from "@/libs/components/time.vue";
import { HandleSQLite } from "@/util/handle_SQLite.js";
import { localSqliteApi } from "@/api/local_sqlite_api.js";
import { mapState, mapActions } from "vuex";
import RecordPopup from "@/components/record-popup/record-popup.vue";

export default {
  name: "componentsIndexList",
  components: {
    multipleOptionsDemo,
    dynamicDemoTemplate,
    timePicker,
    RecordPopup,
  },
  data() {
    return {
      index: 0,
      remarkValue: "",
      Db: new HandleSQLite(localSqliteApi, "main", "table1"),
      // 选项列表数据
      optionsList: [
        {
          title: "喂奶",
          desc: "",
          bg: "K1v6P7L9q6",
          bgbutnColor: "tn-bg-blue--disabled",
          url: "/componentsPage/index-list/base/index-list?type=0",
          icon: "t-icon-naiping5",
          data: [{ remark: "" }],
        },
        {
          title: "辅食",
          desc: "",
          bg: "2Bv7o9y9vo",
          bgbutnColor: "tn-bg-orange--disabled",
          url: "/componentsPage/index-list/base/index-list?type=1",
          icon: "t-icon-fushi2",
          data: [{ remark: "" }],
        },

        {
          title: "尿不湿",
          desc: "",
          bg: "Pngtree",
          bgbutnColor: "tn-bg-purple--disabled",
          url: "/componentsPage/index-list/base/index-list?type=2",
          icon: "t-icon-zhiniaoku",
          data: [{ remark: "" }],
        },
      ],
      value: 0,
      sliderValue: 100,
      show: false,
      mode: "bottom",
      backgroundColor: "",
      width: "80%",
      height: "65%",
      borderRadius: 23,
      closeBtn: true,
      closeBtnIcon: "close",
      closeBtnPosition: "top-right",
      maskCloseable: true,
      popupShowSubsectionIndex: 1,
      birthday: "",
      activeInput: "", // 用于存储当前获得焦点的输入框ID
      username: "baby",
      weatherIcon: "100",
      weatherTemp: "",
    };
  },
  mounted() {
    this.select();
    if (uni.getStorageSync("USER_TOKEN")) {
      const userInfo = this.$store.state.userInfo;
      if (!userInfo || Object.keys(userInfo).length === 0) {
        // 如果 store 中没有用户信息，则重新获取
        this.$store
          .dispatch("getUserInfo")
          .then(() => {
            const updatedUserInfo = this.$store.state.userInfo;
            this.birthday = this.calculateAge(updatedUserInfo.birthday);
            this.username = updatedUserInfo.name;
          })
          .catch((error) => {
            console.error("Failed to get user info:", error);
          });
      } else {
        // 直接使用 store 中的用户信息
        this.birthday = this.calculateAge(userInfo.birthday);
        this.username = userInfo.name;
      }
    }
    this.startDateWatcher();
    this.setWeatherIcon();
  },
  computed: {
    ...mapState(["listDatas", "selectedTime", "userInfo"]),
    groupList() {
      if (!this.listDatas) return {};

      // 获取今天的起止时间
      const today = new Date();
      const todayStart = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate()
      ).getTime();
      const todayEnd = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate() + 1
      ).getTime();

      // 分组数据初始化
      const groupedByType = this.listDatas.reduce((acc, item) => {
        // 如果分组中还没有该 type，则初始化一个数组
        if (!acc[item.type]) {
          acc[item.type] = {
            items: [], // 分组的所有项
            todayCount: 0, // 分组中今日的记录数量
          };
        }

        // 添加到分组
        acc[item.type].items.push(item);

        // 判断是否是今天的数据，若是则计入今日总量
        const itemTime = new Date(item.createTime).getTime();
        if (itemTime >= todayStart && itemTime < todayEnd) {
          acc[item.type].todayCount++;
        }

        return acc;
      }, {});

      // 对每个分组按 createTime 降序排序，并保留最新的一条
      for (const type in groupedByType) {
        groupedByType[type].items = groupedByType[type].items
          .sort((a, b) => new Date(b.createTime) - new Date(a.createTime)) // 按 createTime 降序排序
          .slice(0, 1); // 只保留最新的一条
      }
      // 更新 optionsList，并将今日总量添加进去
      this.optionsList.forEach((option, index) => {
        if (groupedByType[index]) {
          option.data = groupedByType[index].items; // 最新记录
          option.todayCount = groupedByType[index].todayCount; // 今日总量
        } else {
          option.data = [];
          option.todayCount = 0;
        }
      });
      return this.optionsList;
    },
  },
  methods: {
    ...mapActions(["getList"]),
    select() {
      this.getList();
    },
    save(data) {
      let selectedTime = this.selectedTime;
      const now = new Date();
      if (new Date(this.selectedTime) > now) {
        this.$refs.toast.show({
          title: "选择的时间大于当前时间了 ",
          content: "",
          duration: 1500,
        });

        return;
      }

      this.Db.execute("insert", {
        createTime: selectedTime,
        type: data.type,
        remark: data.remark,
        quantity: data.value,
      });
      this.select();
      this.closedPopup();
    },
    click(event) {
      this[event.methods] && this[event.methods](event);
    },
    // 弹出弹框
    showPopup() {
      this.openPopup();
    },

    // 打开Popup
    openPopup() {
      this.show = true;
    },
    // 关闭Popup
    closedPopup() {
      this.show = false;
    },
    addPopup(index) {
      this.index = index;
      this.remarkValue = "";
      this.openPopup();
    },
    currentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从 0 开始计数
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      // 拼接成 YYYY-MM-DD HH:mm 格式
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    calculateAge(birthDateStr) {
      const birthDate = new Date(birthDateStr);
      const currentDate = new Date();

      // 检查日期合法性
      if (isNaN(birthDate)) {
        return "";
      }

      // 计算年、月、日
      let years = currentDate.getFullYear() - birthDate.getFullYear();
      let months = currentDate.getMonth() - birthDate.getMonth();
      let days = currentDate.getDate() - birthDate.getDate();

      // 调整月份
      if (days < 0) {
        months--;
        const prevMonth = new Date(
          currentDate.getFullYear(),
          currentDate.getMonth(),
          0
        ); // 上个月的最后一天
        days += prevMonth.getDate();
      }

      // 调整年份
      if (months < 0) {
        years--;
        months += 12;
      }

      // 返回结果
      years = years > 0 ? years + "岁" : "";
      months = months > 0 ? months + "个月" : "";
      days = days > 0 ? days + "天" : "";
      return `${years}${months}${days}`;
    },
    navigateTo(page) {
      const routes = {
        milk_record: "/componentsPage/index-list/base/index-list?type=0",
        vaccine: "/pages/vaccine/vaccine",
        child_care: "/pages/child/childCare",
        growth_record: "/pages/growth_record/growth_record",
      };
      const url = routes[page];
      if (url) {
        uni.navigateTo({ url: url });
      } else {
        console.error("Invalid page:", page);
      }
    },
    startDateWatcher() {
      const currentDate = new Date();
      const options = { year: "numeric", month: "numeric", day: "numeric" };
      const formattedDate = currentDate
        .toLocaleDateString("en-US", options)
        .replace(/\//g, "-");

      const lastCheckedDate = uni.getStorageSync("lastCheckedDate") || "";
      this.cDate = formattedDate;
      // 如果是新一天，立即刷新页面数据
      if (lastCheckedDate != this.cDate) {
        this.refreshPage();
      }
      // 定时器：每分钟检查一次
      this.dateWatcher = setInterval(() => {
        const today = formattedDate;
        if (uni.getStorageSync("lastCheckedDate") !== today) {
          this.refreshPage();
        }
        this.setWeatherIcon();
      }, 1000 * 60);
    },
    setWeatherIcon() {
      this.getWeather()
        .then((res) => {
          this.weatherIcon = res.now.icon;
          this.weatherTemp = res.now.temp;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    refreshPage() {
      this.cDate = new Date().toISOString().split("T")[0];
      uni.setStorageSync("lastCheckedDate", this.cDate);
      this.birthday = this.calculateAge(this.userInfo.birthday);
      this.select();
    },

    clearDateWatcher() {
      if (this.dateWatcher) {
        clearInterval(this.dateWatcher);
        this.dateWatcher = null;
      }
    },
    scrollToInput(inputId) {
      this.activeInput = inputId;
    },
    handleSave(data) {
      // 处理保存逻辑
      console.log("保存数据:", data);
      this.show = false;
    },
    getWeather() {
      const CITY = "101270101"; // 城市代码
      const API_KEY = "6168898dfa3d49778a5005af143b012c";
      const CACHE_DURATION = 3600000; // 缓存持续时间：1小时（以毫秒为单位）
      const STORAGE_KEYS = {
        time: "lastWeatherTime", // 存储上次请求时间的键
        weather: "weatherIcon", // 存储天气数据的键
      };

      return new Promise((resolve, reject) => {
        try {
          const currentTime = Date.now(); // 获取当前时间（比 new Date().getTime() 更高效）
          const lastRequestTime = uni.getStorageSync(STORAGE_KEYS.time) || 0; // 获取上次请求时间

          // 检查是否在缓存时间内
          if (currentTime - lastRequestTime < CACHE_DURATION) {
            const cachedData = uni.getStorageSync(STORAGE_KEYS.weather); // 获取缓存的数据
            if (cachedData) return resolve(cachedData); // 如果有缓存数据，直接返回
          }

          // 如果缓存无效，则进行API请求
          const url = `https://devapi.qweather.com/v7/weather/now?location=${CITY}&key=${API_KEY}`;

          uni.request({
            url: url,
            success: (response) => {
              // 检查响应状态码
              if (response.data.code === "200") {
                // 更新缓存
                uni.setStorageSync(STORAGE_KEYS.time, currentTime); // 更新请求时间
                uni.setStorageSync(STORAGE_KEYS.weather, response.data); // 更新天气数据
                resolve(response.data); // 返回天气数据
              } else {
                reject(new Error("获取天气数据失败")); // 请求失败
              }
            },
            fail: (error) => {
              console.error("天气API错误:", error); // 处理请求失败
              reject(error);
            },
          });
        } catch (error) {
          console.error("天气API错误:", error); // 捕获其他错误
          reject(error);
        }
      });
    },
  },
  beforeUnmount() {
    this.clearDateWatcher();
    // clearTime
    this.clearTimer();
    // Remove token watcher
    uni.$off("storage");
  },
};
</script>
<style lang="css">
@import "../../static/css/QWeather-Icons/font/qweather-icons.css";
</style>

<style lang="scss" scoped>
.logo-pic {
  background-size: cover;
  background-repeat: no-repeat;
  background-position: top;
  border: 8rpx solid white;
  box-shadow: 0rpx 0rpx 80rpx 0rpx rgba(0, 0, 0, 0.25),
    0rpx 8rpx 20rpx 0rpx rgba(0, 0, 0, 0.15);
  border-radius: 50%;
  overflow: hidden;
  background-color: #ffffff;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
  }
}

.top-backgroup {
  position: relative;

  .backgroud-image {
    width: 100%;
    height: 450rpx;
    filter: brightness(1.1) contrast(1.1);
  }
}

.user-info {
  position: relative;
  z-index: 1;
  margin-top: -120rpx;
  padding: 0 30rpx;

  .user-name {
    font-size: 36rpx;
    color: #333;
    font-weight: 600;
    margin: 16rpx 0;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  }

  .user-desc {
    font-size: 28rpx;
    color: #666;
    line-height: 1.5;
  }
}

.content-box {
  margin-top: 30rpx;
  padding: 0 20rpx;

  .nav-section {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 24rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
    backdrop-filter: blur(10px);
  }
}

.tn-margin-sm {
  margin-top: 20rpx;
}

.list__icon__sub {
  text-align: center;
}

.list__icon__sub text {
  width: 35rpx;
  height: 35rpx;
}

.basic {
  background: linear-gradient(to bottom, #ff9800 0.8%, #f8f8f8 24%);
  //max-height: 100vh;
}

.time-display {
  text-align: center;
  font-family: Arial, sans-serif;
}

.date {
  font-size: 1.5em;
  color: #333;
  margin-bottom: 0.2em;
}

.time {
  font-size: 1.2em;
  color: #666;
}

.period {
  font-weight: bold;
  color: #007bff;
  margin-right: 0.3em;
}

.clock {
  font-family: "Courier New", Courier, monospace;
  font-size: 1.4em;
  letter-spacing: 2px;
  color: #d35400;
}

.tn-slider__custom-block {
  background-color: $tn-color-orange;
  width: 50rpx;
  height: auto;
  line-height: 40rpx;
  padding: 0 5rpx;
  border-radius: 50%;
  text-align: left;
  color: #ffffff;
}

.logo-image {
  padding: 15rpx;
  width: 130rpx;
  height: 130rpx;
  position: relative;
  border-radius: 50%;
}

.icon12 {
  &__item {
    width: 30%;
    background-color: #ffffff;
    border-radius: 10rpx;
    padding: 30rpx;
    margin: 20rpx 10rpx;
    transform: scale(1);
    transition: transform 0.3s linear;
    transform-origin: center center;

    &--icon {
      width: 100rpx;
      height: 100rpx;
      font-size: 60rpx;
      border-radius: 50%;
      margin-bottom: 18rpx;
      position: relative;
      z-index: 1;

      &::after {
        content: " ";
        position: absolute;
        z-index: -1;
        width: 100%;
        height: 100%;
        left: 0;
        bottom: 0;
        border-radius: inherit;
        opacity: 1;
        transform: scale(1, 1);
        background-size: 100% 100%;
        background-image: url(https://resource.tuniaokj.com/images/cool_bg_image/icon_bg.png);
      }
    }
  }
}

.popup-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  position: relative;

  &::before {
    content: "";
    position: absolute;
    top: 16rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 60rpx;
    height: 6rpx;
    background: #e0e0e0;
    border-radius: 4rpx;
  }
}

.popup-inner {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0 30rpx 30rpx;
}

.popup-title {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx 30rpx 24rpx;
  margin-bottom: 20rpx;
  position: relative;

  &::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 30rpx;
    right: 30rpx;
    height: 1px;
    background: linear-gradient(to right, transparent, #f0f0f0, transparent);
  }

  .t-icon {
    font-size: 36rpx;
    color: #ff9800;
    margin-right: 12rpx;
    display: flex;
    align-items: center;
  }

  text {
    font-size: 30rpx;
    color: #2c2c2c;
    font-weight: 500;
    letter-spacing: 1rpx;
  }
}

.form-item {
  margin-bottom: 24rpx;

  .label {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 12rpx;
    font-weight: 500;
  }
}

.button-container {
  margin-top: 40rpx;
  padding: 0 20rpx;
}

.justify-content-item {
  /* 背景色 */
  //width: 100%; /* 宽度平铺 */
  //margin-bottom: 20rpx;
  //box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1); /* 下方阴影 */
  //padding: 20rpx;
}

// .item-container {
// 	display: flex;
// 	align-items: center;
// }

// .logo-pic {
// 	margin-right: 20rpx;
// }

// .logo-image {
// 	border-radius: 50%;
// 	overflow: hidden;
// }

// .tn-shadow-blur {
// 	border-radius: 50%;
// }
</style>
